package in.muton.wicket.model;

import in.muton.edushare.EduShareSession;

import org.apache.cayenne.DataObject;
import org.apache.cayenne.DataObjectUtils;
import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.ObjectId;
import org.apache.cayenne.PersistenceState;
import org.apache.wicket.model.IModel;

import com.edushare.common.orm.CayenneORMInterface;

public class CayenneGenericModel<T> implements IModel<T> {
	private static final long serialVersionUID = 2453355014266990284L;
	private transient T object;
	private ObjectId objectId;
	
	public CayenneGenericModel(T object1){
		setObject(object1);
	}
	
	@SuppressWarnings("unchecked")
	public T getObject() {
		if(object!=null && ((DataObject) object).getPersistenceState() != PersistenceState.HOLLOW){
			return this.object;
		}else if(objectId!=null){
			return (T)DataObjectUtils.objectForPK(getDataContext(),this.objectId);
		}else{
			return null;
		}
	}

	private ObjectContext getDataContext() {
		return ((CayenneORMInterface)EduShareSession.get().
				getSessionORMInterface()).getDataContext();
	}

	public void setObject(T object) {
		if(object == null){
			objectId = null;
			this.object = null;
			return;
		}
		this.objectId = ((DataObject)object).getObjectId();
		this.object = object;
	}

	public void detach() {
		this.object = null;
	}
}
